package com.kasinf.sample.protect.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.kasinf.framework.cache.utils.RedisUtils;
import com.kasinf.framework.common.exception.ServiceException;
import com.kasinf.framework.common.util.json.JsonUtils;
import com.kasinf.framework.idempotent.core.annotation.Idempotent;
import com.kasinf.framework.lock.core.annotation.Lock;
import com.kasinf.framework.ratelimiter.core.annotation.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author : Kaiser
 * @Date: 2025/6/5  20:06
 */
@Slf4j
@RestController
@RequestMapping("test")
public class TestController {


    @PostMapping("xss-form")
    public String xss(String name) {
        return name;
    }

    @PostMapping("xss-json")
    public String xssForJson(@RequestBody Map<String, Object> body) {
        return JsonUtils.toJson(body);
    }

    @Idempotent(timeout = 600)
    @GetMapping("identWithMethod")
    public String identWithMethod() {
        ThreadUtil.sleep(1500);
        return "OK";
    }


    @Lock(waitTime = 10)
    @GetMapping("lock")
    public String lock() {
        ThreadUtil.sleep(1500);
        return "OK";
    }


    @GetMapping("lock2")
    public String lock2() {
        //  业务处理1
        ThreadUtil.safeSleep(1500);

        // 业务处理2，需要枷锁
        boolean flag = RedisUtils.lockAndRun("global:lock:test2", () -> {
            log.info("业务处理2, 加锁处理");
            ThreadUtil.safeSleep(2000);
        });
        if (!flag) {
            throw new ServiceException("获取锁失败");
        }
        return "OK";
    }

    @RateLimiter(count = 10)
    @GetMapping("limit")
    public String limit() {
        return "OK";
    }
}
